package com.jy.wms.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.jy.wms.common.UUIDUtils;
import com.jy.wms.common.annotions.BaseServiceDescribe;
import com.jy.wms.common.base.BaseService;
import com.jy.wms.common.base.DigestUtil;
import com.jy.wms.common.base.ServiceException;
import com.jy.wms.common.base.SucessException;
import com.jy.wms.dao.WmsStockFrozenMapper;
import com.jy.wms.pojo.WmsStock;
import com.jy.wms.pojo.WmsStockFrozen;
import com.jy.wms.pojo.WmsStockFrozenDetailed;
import com.jy.wms.pojo.WmsStockFrozenOperation;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @ClassName: WmsStockFrozenService.java
 * @Description: 库存冻结主表
 * @Author Yjs
 * @Date Fri Dec 01 09:13:54 GMT+08:00 2017
 */

@Service
public class WmsStockFrozenService extends BaseService<WmsStockFrozenMapper, WmsStockFrozen> {
    protected static Logger log = Logger.getLogger(WmsStockFrozenService.class);
    /**
     * 新增库存冻结
     *
     * @param entity 实体对象
     * @return
     */
    @BaseServiceDescribe(moduleName = "库存冻结管理", btnName = "新增库存冻结")
    @Transactional
    public void baseInsert(WmsStockFrozen entity) throws Exception {
        WmsStockFrozen wmsStockFrozen = dao.searchFrozen(entity.getDjdh());
        if (wmsStockFrozen != null) {
            throw new ServiceException("库存冻结单号不可重复");
        } else {
        //冻结单号生成
        /*String djdh = searchDjdh();
        entity.setDjdh(djdh);*/
            //库存冻结记录(用于回滚)
            WmsStockFrozenOperation wmsStockFrozenOperation = null;
            //库存冻结明细集合(用于回滚)
            List<String> wmsStockFrozenDetailedList = new ArrayList<String>();
            //库存集合(用于回滚)
            List<WmsStock> wmsStockList = new ArrayList<WmsStock>();
            //库存冻结主表ID
            String djId = UUIDUtils.uuid();
            Integer count = 0;
            for (WmsStockFrozenDetailed wmsStockFrozenDetailed : entity.getList()) {
                Integer kdjsl = 0;
                //查询库存可冻结数量
                WmsStock wmsStock = dao.searchKdjsl(wmsStockFrozenDetailed.getKcid());
                if (!"".equals(wmsStock.getDjsl()) && wmsStock.getDjsl() != null) {
                    kdjsl = Integer.valueOf(wmsStock.getDjsl());
                }
                Integer kdjsl2 = Integer.valueOf(wmsStockFrozenDetailed.getDjsl());
                //判断冻结数量是否大于库存内可冻结数量
                if (kdjsl2 > kdjsl) {
                    rollBack(wmsStockFrozenOperation, wmsStockFrozenDetailedList, wmsStockList);
                    throw new ServiceException("冻结数量不可大于库存内可冻结数量");
                } else {
                    //添加库存冻结明细
                    wmsStockFrozenDetailed.setId(UUIDUtils.uuid());
                    //冻结ID
                    wmsStockFrozenDetailed.setDjid(djId);
                    wmsStockFrozenDetailed.setCkid(entity.getCkid());
                    wmsStockFrozenDetailed.setHzid(entity.getHzid());
                    //0:冻结 1:解冻
                    wmsStockFrozenDetailed.setZt("0");
                    Integer i = dao.saveDjMx(wmsStockFrozenDetailed);
                    if (i > 0) {
                        wmsStockFrozenDetailedList.add(wmsStockFrozenDetailed.getId());
                        //更改库存内冻结信息
                        i = dao.updateKcDj(wmsStockFrozenDetailed.getKcid(), String.valueOf(wmsStockFrozenDetailed.getDjsl()));
                        if (i > 0) {
                           // log.info("新增库存冻结操作(库存id:" + wmsStock.getId() + ";库存数量:" + wmsStock.getSl() + ";库存原冻结数量:" + kdjsl + ";本次库存冻结数量:" + kdjsl2 + ")");
                            DigestUtil.addStockHistory(wmsStock.getId(),entity.getCjry(),0,0,0,kdjsl2,0,0,7,"库存冻结");
                            count++;
                            wmsStockList.add(wmsStock);
                        } else {
                            rollBack(wmsStockFrozenOperation, wmsStockFrozenDetailedList, wmsStockList);
                            throw new ServiceException("库存冻结数量更改失败");
                        }
                    } else {
                        rollBack(wmsStockFrozenOperation, wmsStockFrozenDetailedList, wmsStockList);
                        throw new ServiceException("库存冻结明细添加失败");
                    }

                }
            }
            if (count.equals(entity.getList().size())) {

                wmsStockFrozenOperation = new WmsStockFrozenOperation();
                wmsStockFrozenOperation.setId(UUIDUtils.uuid());
                //冻结ID
                wmsStockFrozenOperation.setDjid(djId);
                //冻结人员(创建人)
                wmsStockFrozenOperation.setCjry(entity.getCjry());
                //仓库ID
                wmsStockFrozenOperation.setCkid(entity.getCkid());
                //货主ID
                wmsStockFrozenOperation.setHzid(entity.getHzid());
                //添加库存冻结记录信息
                Integer j = dao.saveDjJl(wmsStockFrozenOperation);
                if (j > 0) {
                    entity.setId(djId);
                    entity.setZt("0");
                    j = dao.baseInsert(entity);
                    if (j > 0) {
                        throw new SucessException("库存冻结添加成功");
                    } else {
                        rollBack(wmsStockFrozenOperation, wmsStockFrozenDetailedList, wmsStockList);
                        throw new ServiceException("库存冻结添加失败");
                    }
                } else {
                    rollBack(wmsStockFrozenOperation, wmsStockFrozenDetailedList, wmsStockList);
                    throw new ServiceException("库存冻结记录添加失败");
                }
            } else {
                rollBack(wmsStockFrozenOperation, wmsStockFrozenDetailedList, wmsStockList);
                throw new ServiceException("库存冻结明细条数与添加条数不符");
            }
        }
    }

    /**
     * 查询可冻结库存货品
     * 选择库存的库位类型只能为“0存储库位”、“2箱拣货位”、“1件拣货位”、“3箱/件拣货位”
     *
     * @param entity
     * @return
     * @throws Exception
     */
    public Page<WmsStockFrozenDetailed> searchHp(WmsStockFrozenDetailed entity) throws Exception {
        try {

           /*
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String cjsj_start = null;
            String cjsj_end = null;
           if (entity.getScrq_start() != null && !"".equals(entity.getScrq_start())) {
                cjsj_start = sdf.format(new Date(Long.valueOf(entity.getScrq_start())));
            }
            if (entity.getScrq_end() != null && !"".equals(entity.getScrq_end())) {
                cjsj_end = sdf.format(new Date(Long.valueOf(entity.getScrq_end())));
            }
            entity.setScrq_start(cjsj_start);
            entity.setScrq_end(cjsj_end);*/
            PageHelper.startPage(entity.getPage(), entity.getRows());
            List<String> stringList = new ArrayList<String>();
            //库位类型只能为“存储库位”、“箱拣货位”、“件拣货位”、“箱/件拣货位”
            stringList.add("0");
            stringList.add("1");
            stringList.add("2");
            stringList.add("3");
            return (Page<WmsStockFrozenDetailed>) dao.searchHp(entity, stringList);
        } catch (Exception e) {
            throw new ServiceException("查询可冻结库存货品失败");
        }
    }

    /**
     * 解冻专用查询库存冻结明细信息
     *
     * @param entity
     * @return
     * @throws Exception
     */
    public Page<WmsStockFrozenDetailed> searchFrozenMx(WmsStockFrozen entity) throws Exception {
        try {
            PageHelper.startPage(entity.getPage(), entity.getRows());
            //冻结状态 0:冻结 1:解冻
            entity.setZt("0");
            return (Page<WmsStockFrozenDetailed>) dao.searchFrozenMx(entity);
        } catch (Exception e) {
            throw new ServiceException("查询可冻结库存货品失败");
        }
    }

    /**
     * 库存冻结明细解冻
     *
     * @param wmsStockFrozen
     * @throws Exception
     */
    @BaseServiceDescribe(moduleName = "库存解冻管理", btnName = "库存解冻")
    @Transactional
    public void stockThaw(WmsStockFrozen wmsStockFrozen, String name, String ckid, String hzid) throws Exception {
        WmsStockFrozenOperation wmsStockFrozenOperation = null;
        //库存冻结明细集合(用于回滚)存明细ID
        List<String> stringList = new ArrayList<String>();
        //库存集合(用于回滚)
        List<WmsStock> wmsStockList = new ArrayList<WmsStock>();
        WmsStock wmsStock = null;
        Integer i = 0;
        if (wmsStockFrozen.getList().size() > 0) {
            for (WmsStockFrozenDetailed wmsStockFrozenDetailed : wmsStockFrozen.getList()) {
                //查询库存冻结明细
                WmsStockFrozenDetailed wmsStockFrozenDetailed1 = dao.searchMx(wmsStockFrozenDetailed.getId(), "0");
                //冻结
                if ("0".equals(wmsStockFrozenDetailed1.getZt())) {
                    Integer djsls = 0;
                    //计算解冻的数量
                    Integer djsl = wmsStockFrozenDetailed1.getDjsl() - Integer.parseInt(wmsStockFrozenDetailed.getKdjsl());
                    //冻结状态 0:冻结 1:解冻
                    String zt = "0";
                    if (djsl > 0) {
                        zt = "0";
                        //更改状态为冻结
                        i = dao.stockThaw(wmsStockFrozenDetailed1.getId(), zt, djsl);
                    } else if (djsls.equals(djsl)) {
                        zt = "1";
                        //更改状态为解冻
                        i = dao.stockThaw(wmsStockFrozenDetailed1.getId(), zt, djsl);
                    } else {
                        throw new ServiceException("解冻数量不可大于冻结数量");
                    }
                    if (i > 0) {
                        stringList.add(wmsStockFrozenDetailed1.getId());
                        //更改库存冻结数量,总数量
                        i = dao.updateKcDj2(wmsStockFrozenDetailed1.getKcid(), Integer.parseInt(wmsStockFrozenDetailed.getKdjsl()));
                        if (i > 0) {
                            //查询库存可冻结数量
                            wmsStock = dao.searchKdjsl(wmsStockFrozenDetailed1.getKcid());
                          //  log.info("库存解冻操作(库存id:" + wmsStock.getId() + ";库存数量:" + wmsStock.getSl() + ";库存原冻结数量:" + wmsStock.getDjsl() + ";本次库存解冻数量:" + wmsStockFrozenDetailed.getKdjsl() + ")");
                            DigestUtil.addStockHistory(wmsStock.getId(),name,0,0,0, Integer.valueOf(wmsStockFrozenDetailed.getKdjsl()),0,0,7,"库存解冻");

                        } else {
                            throw new ServiceException("库存冻结数量更改失败");
                        }
                    } else {
                        throw new ServiceException("库存冻结明细解冻失败");
                    }
                }
            }
            /*//更改库存冻结记录(解冻人)
            wmsStockFrozenOperation = new WmsStockFrozenOperation();
            wmsStockFrozenOperation.setId(UUIDUtils.uuid());
            //冻结ID
            wmsStockFrozenOperation.setDjid(setAndModifyModel.getId());
            //仓库ID
            wmsStockFrozenOperation.setCkid(ckid);
            //解冻人员
            wmsStockFrozenOperation.setJdry(name);
            //货主ID
            wmsStockFrozenOperation.setHzid(hzid);*/
            //更改库存冻结记录信息
            i = dao.updateFrozenJl(wmsStockFrozen.getId(), name);
            if (i > 0) {
                //查询库存冻结主表内是否有冻结的明细
                List<WmsStockFrozenDetailed> list = dao.searchMx2("0", wmsStockFrozen.getId());
                List<WmsStockFrozenDetailed> list2 = dao.searchMx2(null, wmsStockFrozen.getId());
                //冻结状态 0:全部冻结 1：部分冻结 2：全部解冻
                String zt;
                Integer size = list.size();
                Integer size2 = list2.size();
                Integer size3 = 0;
                if (size.equals(size2)) {
                    zt = "0";
                } else if (size.equals(size3)) {
                    zt = "2";
                } else {
                    zt = "1";
                }
                //0:冻结 1：部分冻结 2：全部解冻
                i = dao.updateFrozen(wmsStockFrozen.getId(), zt);
                if (i > 0) {
                    throw new SucessException("库存冻结主表更改成功");
                } else {
                    throw new ServiceException("库存冻结主表更改失败");
                }
            } else {
                throw new ServiceException("库存冻结记录添加失败");
            }
        } else {
            throw new ServiceException("请至少选择一条可解冻的明细");
        }
    }
    /**
     * 插入一条记录（匹配有值的字段）
     *
     * @param entity 实体对象
     * @return int
     */
    public Integer baseInsertSelective(WmsStockFrozen entity) {
        return dao.baseInsertSelective(entity);
    }

    /**
     * 删除（根据主键ID删除）
     *
     * @param id 主键
     * @return int
     */
    public Integer baseDeleteByPrimaryKey(String id) {
        return dao.baseDeleteByPrimaryKey(id);
    }

    /**
     * 删除（根据ID 批量删除）
     *
     * @param idList 主键ID列表
     * @return int
     */
    public Integer baseDeleteBathPrimaryKeys(List<String> idList) {
        return dao.baseDeleteBathPrimaryKeys(idList);
    }

    /**
     * 分页查询
     *
     * @param entity 实体
     * @return Page<WmsStockFrozen>
     */
    @BaseServiceDescribe(moduleName = "查询库存冻结管理", btnName = "分页查询库存冻结")
    public Page<WmsStockFrozen> baseSelectPage(WmsStockFrozen entity) throws ServiceException {
        try {
            /*SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String cjsj_start = null;
            String cjsj_end = null;
            if (entity.getCjsj_start() != null && !"".equals(entity.getCjsj_start())) {
                cjsj_start = sdf.format(new Date(Long.valueOf(entity.getCjsj_start())));
            }
            if (entity.getCjsj_end() != null && !"".equals(entity.getCjsj_end())) {
                cjsj_end = sdf.format(new Date(Long.valueOf(entity.getCjsj_end())));
            }
            String jdsj_start = null;
            String jdsj_end = null;
            if (entity.getJdsj_start() != null && !"".equals(entity.getJdsj_start())) {
                jdsj_start = sdf.format(new Date(Long.valueOf(entity.getJdsj_start())));
            }
            if (entity.getJdsj_end() != null && !"".equals(entity.getJdsj_end())) {
                jdsj_end = sdf.format(new Date(Long.valueOf(entity.getJdsj_end())));
            }
            entity.setCjsj_start(cjsj_start);
            entity.setCjsj_end(cjsj_end);
            entity.setJdsj_start(jdsj_start);
            entity.setJdsj_end(jdsj_end);*/
            PageHelper.startPage(entity.getPage(), entity.getRows());
            return (Page<WmsStockFrozen>) dao.baseSelectPage(entity);
        } catch (Exception e) {
            throw new ServiceException("查询库存冻结失败", e);
        }
    }

    /**
     * 查询（根据主键ID查询）
     *
     * @param id 主键ID
     * @return WmsStockFrozen
     */
    public WmsStockFrozen baseSelectByPrimaryKey(String id) {
        return dao.baseSelectByPrimaryKey(id);
    }

    /**
     * 查询（根据ID 批量查询）
     *
     * @param idList 主键ID列表
     * @return list
     */
    public Integer baseSelectBathPrimaryKeys(List<WmsStockFrozen> idList) {
        return dao.baseSelectBathPrimaryKeys(idList);
    }

    /**
     * 修改 （匹配有值的字段）
     *
     * @param entity 主键ID列表
     * @return int
     */
    public Integer baseUpdateByPrimaryKeySelective(WmsStockFrozen entity) {
        return dao.baseUpdateByPrimaryKeySelective(entity);
    }

    /**
     * 修改（根据主键ID修改）
     *
     * @param entity 主键ID列表
     * @return int
     */
    public Integer baseUpdateByPrimaryKey(WmsStockFrozen entity) {
        return dao.baseUpdateByPrimaryKey(entity);
    }

    /**
     * //回滚专用
     *
     * @param wmsStockFrozenOperation 库存冻结记录(用于回滚)
     * @param wmsStockFrozenDetailedList  库存冻结明细集合(用于回滚)
     * @param wmsStockList                库存集合(用于回滚)
     */
    public void rollBack(WmsStockFrozenOperation wmsStockFrozenOperation, List<String> wmsStockFrozenDetailedList, List<WmsStock> wmsStockList) {
        //删除冻结明细数据
        dao.deleteMx(wmsStockFrozenDetailedList);
        //删除冻结记录数据
        if (wmsStockFrozenOperation != null) {
            dao.deleteJl(wmsStockFrozenOperation);
        }
        for (WmsStock wmsStock : wmsStockList) {
            //还原库存冻结数量
            dao.updateKc(wmsStock);
        }
    }

    /**
     * 导出库存冻结信息查询
     *
     * @param entity
     * @return
     */
    public List<WmsStockFrozen> exportWmsStockFrozen(WmsStockFrozen entity) {
        /*String cjsj_start = entity.getCjsj_start();
        String cjsj_end = entity.getCjsj_end();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        //创建时间开始(冻结时间)
        if (cjsj_start != null && cjsj_start != "") {
            cjsj_start = sdf.format(new Date(Long.valueOf(cjsj_start)));
        }
        //创建时间结束(冻结时间)
        if (cjsj_end != null && cjsj_end != "") {
            cjsj_end = sdf.format(new Date(Long.valueOf(cjsj_end)));
        }
        entity.setCjsj_start(cjsj_start);
        entity.setCjsj_end(cjsj_end);
        String jdsj_start = entity.getJdsj_start();
        String jdsj_end = entity.getJdsj_end();
        //解冻时间开始
        if (jdsj_start != null && jdsj_start != "") {
            jdsj_start = sdf.format(new Date(Long.valueOf(jdsj_start)));
        }
        //解冻时间结束
        if (jdsj_end != null && jdsj_end != "") {
            jdsj_end = sdf.format(new Date(Long.valueOf(jdsj_end)));
        }
        entity.setJdsj_start(jdsj_start);
        entity.setJdsj_end(jdsj_end);*/
        return dao.exportWmsStockFrozen(entity);
    }

    /**
     * 生成库存冻结单号
     *
     * @return
     */
    public String searchDjdh() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        Date time = new Timestamp(System.currentTimeMillis());
        String djdhTime = sdf.format(time);
        //模糊查询装车单编号
        String djdh = dao.searchDjdh(djdhTime);
        //如果数据库内有装车单编号
        if (!"".equals(djdh) && djdh != null) {
            String[] maxNum = djdh.split(djdhTime);
            //取到日期后面的最大值
            long maxDjdh = Long.parseLong(maxNum[1]);
            //最大值加1
            maxDjdh += 1;
            djdh = djdhTime + maxDjdh;
        } else {
            djdh = djdhTime + "1";
        }
        return djdh;
    }

}
